<?php


namespace App\Repositories;


use App\Models\Package as Model;
use App\Traits\Logs;
use Exception;
use LTools\Repositories\RepositoryAbstract;
use Throwable;

class Package extends RepositoryAbstract
{
    use Logs;

    /**
     * Package constructor.
     * @param Model $model
     * @author luffyzhao@vip.126.com
     */
    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    /**
     * @param array $attributes
     * @return \App\Models\Consumable|bool|\Illuminate\Database\Eloquent\Model
     */
    public function create(array $attributes = [])
    {
        /** @var Model $model */
        $model = parent::create($attributes); // TODO: Change the autogenerated stub
        $this->recordLogs($model, '创建[' . $model->getAttribute('name') . ']成功!');
        return $model;
    }

    /**
     * @param $id
     * @param array $values
     * @return bool|\Illuminate\Database\Eloquent\Model|void
     * @throws Throwable
     */
    public function update($id, array $values)
    {
        /** @var \App\Models\Consumable $model */
        $model = $this->find($id);
        $model->fill($values)->saveOrFail();
        $this->recordLogs($model, '修改[' . $model->getAttribute('name') . ']成功!');
        return $model;
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
     */
    public function show($id)
    {
        /** @var Model $model */
        return $this->model->with(['logs.user', 'stocks'])->findOrFail($id);
    }

    /**
     * 减库存
     * @param int $id
     * @param int $value
     * @return Model
     * @throws Exception
     * @author luffyzhao@vip.126.com
     */
    public function decrementStocks(int $id, int $value)
    {
        try{
            /** @var Model $model */
            $model = $this->find($id);
            $model->decrement('stock', $value);
            return $model;
        }catch (Exception | Throwable $exception){
            throw new Exception(sprintf("箱子[%s]库存不足", $model->getAttribute('name')));
        }
    }
}